<template>
  <div class="card-manager-wrap">
    <van-dialog id="van-dialog" />
    <van-tabs :active="active" @change="onChange">
      <van-tab title="听力">
        <card-manager-list
          @editCard="editCard"
          @delCard="delCard"
          @switchCard="switchCard"
          @addCard="addCard"
          v-if="active === 0"
          type="listening"
          :data="listDataListening"
        />
      </van-tab>
      <van-tab title="口语">
        <card-manager-list
          v-if="active === 1"
          type="speaking"
          @editCard="editCard"
          @delCard="delCard"
          @switchCard="switchCard"
          @addCard="addCard"
          :data="listDataSpeaking"
        />
      </van-tab>
      <van-tab title="阅读">
        <card-manager-list
          v-if="active === 2"
          type="reading"
          @editCard="editCard"
          @delCard="delCard"
          @switchCard="switchCard"
          @addCard="addCard"
          :data="listDataReading"
        />
      </van-tab>
      <van-tab title="写作">
        <card-manager-list
          v-if="active === 3"
          type="writing"
          @editCard="editCard"
          @delCard="delCard"
          @switchCard="switchCard"
          @addCard="addCard"
          :data="listDataWriting"
        />
      </van-tab>
    </van-tabs>
    <van-dialog
      class="custom-dialog"
      use-slot
      :show="showAddDialog"
      @close="modalClose"
      :show-confirm-button="false"
    >
      <div class="add-dialog-content">
        <div class="close-btn" @click.stop="modalClose"></div>
        <div class="dialog-icon" :style="'background-image:url('+addCardbackgroundUrl+')'"></div>
        <div class="dialog-text">定制自己的{{chineseType}}卡片</div>
        <div class="dialog-input-container">
          <van-field
            :value="dialogInputVal"
            @change="(ev) => {dialogInputVal = ev.mp.detail}"
            placeholder="请输入卡片名称"
            :border="false"
            :maxlength="10"
          />
        </div>
        <van-button
          type="primary"
          block
          round
          class="dialog-btn"
          size="small"
          color="#ffa722"
          @click="confirmAddCard"
        >完成</van-button>
      </div>
    </van-dialog>
    <my-loading v-if="loadingStatus"/>
  </div>
</template>

<script>
import cardManagerList from "./components/cardManagerList";
import cloudHandler from "../../cloud/index";
import swiperComponent from "../index/components/swiperComponent";
import Dialog from "../../../static/vant/dialog/dialog";
import myLoading from '../../components/loading';
export default {
  data() {
    return {
      active: 0,
      addType: "",
      showAddDialog: false,
      dialogInputVal: "",
      listData: [],
      targetCardId: "",
      loadingStatus: false
    };
  },
  computed: {
    addCardbackgroundUrl() {
      if (!this.addType) return '';
      const urlMap = {
        listening: "定制-听力@2x.png",
        reading: "定制-阅读@2x.png",
        writing: "定制-写作@2x.png",
        speaking: "定制-口语@2x.png"
      };
      const baseUrl = "http://cdn1.ielts.group/";
      return this.addType && (baseUrl + urlMap[this.addType]);
    },
    listDataReading() {
      if (!this.listData.length) return [];
      return this.listData
        .filter(item => item.cardType === "reading")
        .sort(
          (a, b) =>
            new Date(b.created_time).getTime() -
            new Date(a.created_time).getTime()
        );
    },
    listDataListening() {
      if (!this.listData.length) return [];
      return this.listData
        .filter(item => item.cardType === "listening")
        .sort(
          (a, b) =>
            new Date(b.created_time).getTime() -
            new Date(a.created_time).getTime()
        );
      // .sort((a, b) => b.active - a.active);
    },
    listDataWriting() {
      if (!this.listData.length) return [];
      return this.listData
        .filter(item => item.cardType === "writing")
        .sort(
          (a, b) =>
            new Date(b.created_time).getTime() -
            new Date(a.created_time).getTime()
        );
      // .sort((a, b) => b.active - a.active);
    },
    listDataSpeaking() {
      if (!this.listData.length) return [];
      return this.listData
        .filter(item => item.cardType === "speaking")
        .sort(
          (a, b) =>
            new Date(b.created_time).getTime() -
            new Date(a.created_time).getTime()
        );
      // .sort((a, b) => b.active - a.active);
    },
    chineseType() {
      const chineseMap = {
        listening: "听力",
        reading: "阅读",
        writing: "写作",
        speaking: "口语"
      };
      return this.addType && chineseMap[this.addType];
    }
  },
  methods: {
    showLoading() {
      this.loadingStatus = true;
    },
    hideLoading() {
      this.loadingStatus = false;
    },
    onChange(event) {
      // 索引更改
      this.active = event.mp.detail.index;
    },
    modalClose(ev) {
      this.showAddDialog = false;
    },
    addCard(type) {
      this.addType = type;
      this.targetCardId = "";
      this.dialogInputVal = "";
      this.showAddDialog = true;
    },
    confirmAddCard({ active }) {
      const isSwitch = typeof active === "boolean";
      if (this.checkDialogInputVal() || isSwitch) {
        // 新增
        const query1 = {
          title: this.dialogInputVal,
          active: true,
          cardClassify: "custom",
          cardType: this.addType,
          needScore: false
        };
        // 编辑
        const query2 = {
          title: this.dialogInputVal,
          _id: this.targetCardId
        };
        // 修改激活状态
        const query3 = {
          active,
          _id: this.targetCardId
        };
        let query;
        let type;
        if (!this.targetCardId) {
          type = 1;
          query = query1;
        } else if (isSwitch) {
          type = 3;
          query = query3;
        } else {
          type = 2;
          query = query2;
        }
        this.showLoading();
        this.modalClose();
        cloudHandler
          .postCard(query)
          .then(() => {
            this.getCardLists();
          })
          .catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.hideLoading();
          })
      }
    },
    checkDialogInputVal() {
      const val = this.dialogInputVal;
      if (!val) {
        // 未填写
        return false;
      }
      if (val.length > 15) {
        // 字符大于15
        return false;
      }
      return true;
    },
    getCardLists() {
      cloudHandler
        .getCardLists("all")
        .then(res => {
          if (res.body) this.listData = res.body;
        })
        .catch(err => {
          console.log(err);
        });
    },
    commitCard(data) {
      // 提交修改card信息
      this.showLoading();
      cloudHandler
        .postCard(data)
        .then(() => {
          this.getCardLists();
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {
          this.hideLoading();
        })
    },

    editCard(item) {
      this.targetCardId = item._id;
      this.dialogInputVal = item.title;
      this.addType = item.cardType;
      this.showAddDialog = true;
    },
    async delCard(item) {
      const _id = item._id;
      try {
        await Dialog.confirm({
          title: "警告",
          message: "删除后，卡片无法回复，您确定要执行此操作吗？"
        });
        this.showLoading();
        await cloudHandler
          .delCard(_id)
          .then(() => {
            this.getCardLists();
          })
          .catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.hideLoading();
          })
      } catch (err) {
        console.log(err);
      }
    },
    switchCard(item) {
      // 先变
      this.targetCardId = item._id;
      this.confirmAddCard({ active: !item.active });
      this.$set(item, "active", !item.active);
    }
  },
  components: {
    cardManagerList,
    swiperComponent,
    myLoading
  },
  created() {
    this.getCardLists();
  },
  onLoad(ev) {
    if (ev.add &&ev.cardType) {
      if (ev.cardType === 'all') return; // todo
      this.addCard(ev.cardType);
    }
  },
  onShow() {
    this.getCardLists();
  }
};
</script>

<style lang="less">
// 重写tabs样式
.card-manager-wrap {
  .van-tabs__line {
    background-color: #ffa722;
  }
  .van-tab--active {
    color: #3d475c !important;
  }
  .van-tab {
    color: #969799;
  }
  .van-hairline--top-bottom:after {
    border: none !important;
  }
  .van-dialog__cancel,
  .van-dialog__confirm {
    background: #ffd733 !important;
  }
  .add-dialog-content {
    height: 214px;
    width: 271px;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    .close-btn {
      position: absolute;
      width: 16px;
      height: 16px;
      background:url(http://cdn.ielts.group/close-btn.png) center center no-repeat;
      background-size: cover;
      right: 10px;
      top: 10px;
    }
    .dialog-icon {
      width: 45px;
      height: 45px;
      border-radius: 50%;
      background: #fff;
      margin-top: 20px;
      margin-bottom: 10px;
      background-position: center center;
      background-size: 60%;
      background-repeat: no-repeat;
    }
    .dialog-text {
      color: #3d475c;
      font-size: 14px;
      font-weight: 600;
    }
    .dialog-input-container {
      width: 160px;
      .van-cell {
        background: transparent;
        border-bottom: 1px solid #3d475c;
        padding-bottom: 2px;
      }
    }
    .dialog-btn {
      margin: 25px 15px 0 15px;
      width: calc(100% - 30px);
    }
  }
}
</style>
